package cn.xicode.cloud.frame.dubbo.common.provider.filter;

import cn.xicode.cloud.frame.dubbo.common.provider.TraceIdUtil;
import cn.xicode.cloud.frame.dubbo.common.provider.TraceLogConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;

/**
 * @author LGC
 * @see <a href="https://github.com/apache/dubbo/issues/8365">...</a>
 * Consumer 端使用 getClientAttachment，
 * Provider 端使用 getServerAttachment，
 * Consumer 端获取 Provider 端返回上下文使用 getServerContext。
 * <p>
 * getClientAttachment ( A --> B , in A side)
 * getServerAttachment ( A --> B , in B side)
 * getServerContext ( A <-- B , in B side)
 * <p>
 * Consumer setValue --> Provider getValue
 * Consumer：RpcContext.getClientAttachment().setAttachment(WebConstEnum.Model.TP_NUM,MDC.get(WebConstEnum.Model.TP_NUM));
 * Provider ：RpcContext.getServerAttachment().getAttachment(WebConstEnum.Model.TP_NUM);
 * <p>
 * Provider setValue --> Consumer getValue
 * Provider ： result.setAttachment(WebConstEnum.Model.TIMESTAMP,""+l);
 * or
 * RpcContext.getServerContext().setAttachment(WebConstEnum.Model.TIMESTAMP,""+System.currentTimeMillis());
 * Consumer：result.getAttachment(WebConstEnum.Model.TIMESTAMP,"-1");
 */

@Slf4j
@Activate(group = CommonConstants.CONSUMER)
public class DubboComsumerFilter implements Filter {


    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        String traceId = TraceIdUtil.getTraceId();
        RpcContext.getClientAttachment().setAttachment(TraceLogConstants.TRACE_ID, traceId);
        log.info("消费端设置traceId值到服务端：{}", traceId);

        Result result = invoker.invoke(invocation);
//        String aa = result.getAttachment("aa");
//        log.info("消费端获取服务端值aa:{}", aa);
        return result;
    }

}
